import axios from 'axios'
import { userStore } from '@/pinia/modules/user';
import { xmtoast, xmloading } from './public';
//创建axios的一个实例 
const baseURL = import.meta.env.VITE_HTTP;
const instance = axios.create({
    headers: {
        'Content-Type': 'application/json'
    },
    baseURL,//接口统一域名
    timeout: 12000
})
//------------------- 一、请求拦截器
instance.interceptors.request.use(function (config: any) {
    let {method} = config
    const userToken = userStore().user_id;
    if(method == 'get') {
        config.params['user_id'] = userToken;
    }
    if(method == 'post') {
        config.data['user_id'] = userToken;
    }
    return config;
}, function (error: any) {
    return Promise.reject(error);
});

//----------------- 二、响应拦截器
instance.interceptors.response.use(function (response: any) {
    const { msg, code} = response.data
    if(code == 0) {
        return Promise.resolve({...response.data});
    }else {
        let tips = ''
        if(Array.isArray(msg)){
            tips = 'code:' + code
        } else {
            tips = msg
        }
        xmloading().close()
        xmtoast(tips)
        return Promise.reject(code);
    } 

}, function (error: any) {
    // 对响应错误做点什么
    xmloading().close()
    xmtoast('当前网络异常，请稍后再试')
    return Promise.reject(error);
});

export default instance
